package cn.edu.zime.tjh.iotapp;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import org.json.JSONException;
import org.json.JSONObject;

import cn.edu.zime.tjh.iotapp.api.ApiCallback;
import cn.edu.zime.tjh.iotapp.api.ApiService;

import android.Manifest;
import android.content.pm.PackageManager;
import java.util.ArrayList;
import java.util.List;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private static final int PERMISSION_REQUEST_CODE = 100;
    private String[] requiredPermissions = {
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.CAMERA,
        Manifest.permission.INTERNET,
        Manifest.permission.ACCESS_NETWORK_STATE
    };

    private EditText etUsername, etPassword;
    private Button btnLogin;
    private Button btnRegister;
    private Button btnFindPwd;
    private TextView tvMessage;
    private CheckBox cbRememberPassword;

    private ApiService apiService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // 初始化API服务
        apiService = ApiService.getInstance();

        // 初始化视图
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        btnLogin = findViewById(R.id.btnLogin);
        btnFindPwd = findViewById(R.id.btnFindPwd);
        tvMessage = findViewById(R.id.tvMessage);
        cbRememberPassword = findViewById(R.id.cbRememberPassword);

        //注册点击
        btnRegister = findViewById(R.id.btnRegister);
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到注册界面
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
        
        // 找回密码按钮点击事件
        btnFindPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到找回密码界面
                Intent intent = new Intent(LoginActivity.this, FindPwdActivity.class);
                startActivity(intent);
            }
        });

        // 登录按钮点击事件
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = etUsername.getText().toString();
                String password = etPassword.getText().toString();

                if (username.isEmpty() || password.isEmpty()) {
                    tvMessage.setText("用户名和密码不能为空");
                    tvMessage.setVisibility(View.VISIBLE);
                } else {
                    // 发起登录请求
                    Log.d(TAG, "开始登录用户: " + username);
                    login(username, password);
                }
            }
        });

        // 尝试从SharedPreferences获取保存的用户名和密码
        loadSavedCredentials();

        // 检查并请求权限
        checkAndRequestPermissions();
    }

    private void login(String username, String password) {
        Log.d(TAG, "调用登录API，用户名: " + username);
        
        apiService.login(username, password, new ApiCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                Log.d(TAG, "登录成功: " + response.toString());
                
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            // 解析服务器返回的 JSON 数据
                            String message = "登录成功";
                            String accessToken = "";
                            String role = "user";
                            
                            if (response.has("message")) {
                                message = response.getString("message");
                            }
                            
                            // 获取access_token和role
                            if (response.has("data")) {
                                JSONObject data = response.getJSONObject("data");
                                if (data.has("access_token")) {
                                    accessToken = data.getString("access_token");
                                }
                                if (data.has("role")) {
                                    role = data.getString("role");
                                }
                            }
                            
                            // 保存用户信息到SharedPreferences
                            saveUserInfo(username, accessToken, role);
                            
                            // 提示登录成功
                            Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
                            
                            // 检查是否为管理员账号
                            if (isAdminAccount(username)) {
                                // 如果是管理员账号，跳转到管理界面
                                Intent intent = new Intent(LoginActivity.this, AdminActivity.class);
                                startActivity(intent);
                            } else {
                                // 如果是普通用户，跳转到主界面
                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                startActivity(intent);
                            }
                            finish();
                        } catch (JSONException e) {
                            Log.e(TAG, "JSON解析错误: " + e.getMessage());
                            e.printStackTrace();
                            tvMessage.setText("服务器返回数据格式错误");
                            tvMessage.setVisibility(View.VISIBLE);
                        }
                    }
                });
            }

            @Override
            public void onFailure(String errorMsg) {
                Log.e(TAG, "登录失败: " + errorMsg);
                
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvMessage.setText("登录失败: " + errorMsg);
                        tvMessage.setVisibility(View.VISIBLE);
                    }
                });
            }
        });
    }
    
    /**
     * 保存用户信息到SharedPreferences
     */
    private void saveUserInfo(String username, String accessToken, String role) {
        SharedPreferences preferences = getSharedPreferences("user_info", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        
        // 保存用户信息
        editor.putString("username", username);
        editor.putString("access_token", accessToken);
        editor.putString("role", role);
        editor.putBoolean("is_logged_in", true);
        
        // 检查用户是否选择了"记住密码"
        if (cbRememberPassword.isChecked()) {
            // 获取用户输入的密码
            String password = etPassword.getText().toString();
            
            // 保存用户名和密码
            SharedPreferences credPreferences = getSharedPreferences("user_credentials", MODE_PRIVATE);
            SharedPreferences.Editor credEditor = credPreferences.edit();
            
            credEditor.putString("saved_username", username);
            credEditor.putString("saved_password", password);
            credEditor.putBoolean("is_credentials_saved", true);
            
            credEditor.apply();
            
            Log.d(TAG, "用户凭据已保存");
        } else {
            // 如果用户取消了"记住密码"，则清除保存的凭据
            clearSavedCredentials();
        }
        
        // 提交修改
        editor.apply();
        
        Log.d(TAG, "用户信息已保存: " + username + ", 角色: " + role);
    }

    // 清除保存的凭据
    private void clearSavedCredentials() {
        SharedPreferences preferences = getSharedPreferences("user_credentials", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.clear();
        editor.apply();
        
        Log.d(TAG, "用户凭据已清除");
    }

    // 添加判断是否为管理员账号的方法
    private boolean isAdminAccount(String username) {
        // 这里可以根据实际需求实现管理员账号的判断逻辑
        // 简单示例：用户名包含"admin"的视为管理员账号
        return username.toLowerCase().contains("admin");
    }

    public void back(View V){
        finish();
    }

    // 添加权限检查和请求方法
    private void checkAndRequestPermissions() {
        List<String> permissionsNeeded = new ArrayList<>();
        
        // 检查哪些权限尚未授予
        for (String permission : requiredPermissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsNeeded.add(permission);
            }
        }
        
        // 如果有未授予的权限，请求它们
        if (!permissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(
                this, 
                permissionsNeeded.toArray(new String[0]), 
                PERMISSION_REQUEST_CODE
            );
        }
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allGranted = true;
            
            // 检查是否所有请求的权限都已授予
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }
            
            if (allGranted) {
                // 所有权限都已授予，可以正常使用应用
                Toast.makeText(this, "所有权限已授予，应用可以正常使用", Toast.LENGTH_SHORT).show();
            } else {
                // 有些权限被拒绝，提示用户
                Toast.makeText(this, "某些功能可能受限，请在设置中启用所需权限", Toast.LENGTH_LONG).show();
            }
        }
    }

    // 添加加载保存的凭据方法
    private void loadSavedCredentials() {
        SharedPreferences preferences = getSharedPreferences("user_credentials", MODE_PRIVATE);
        boolean isCredentialsSaved = preferences.getBoolean("is_credentials_saved", false);
        
        if (isCredentialsSaved) {
            String savedUsername = preferences.getString("saved_username", "");
            String savedPassword = preferences.getString("saved_password", "");
            
            // 填充用户名和密码
            etUsername.setText(savedUsername);
            etPassword.setText(savedPassword);
            
            // 勾选"记住密码"
            cbRememberPassword.setChecked(true);
        }
    }
}